<?php
// $Id$

/**
 * Controller_Admin_Category 控制器
 */
class Controller_Admin_Category extends Controller_Abstract
{

	function actionIndex()
	{
        $cate = $this->_app->currentCategory();
        $this->_view['cate'] = $cate;
	}
	
	function actionCreate(){
		
		$parentCate = Category::find('category_id=?',$this->_context->parent_id)->getOne();
		if($parentCate->id()){
			$sort = $parentCate->subCates->count();
			$parent_id = $parentCate->id();
		}else{
			$sort = 0;
			$parent_id = Category::rootNodeId();
		}
		
		
		$data = array(
			'parent_id' => $parent_id ,
			'name' => $this->_context->name ,
			'sort' => $sort,
		);
 
 		try{
 			$cate = new Category($data);
            $cate->save();

            $ret = array(
                'ack' => 'success',
                'newCateId' => $cate->id(),
            );

            Category::cleanCache();
   		 		
 		}catch(Exception $e){
 			
 			$ret = array(
 				'ack' => 'error',
 				'errorMsg' => $e->getMessage(),
 			);
 		} 
 		
 		return json_encode($ret);
 	}

    function actionSave(){
        $cate = Category::findById($this->_context->cid)->getOne();
        if($cate->id()){
            $cate->changeProps($_POST)->save();
            $url = url('/edit', 'cid/'.$cate->id());
            return $this->_redirect($url);
        }else{
            throw new Exception('Invalid category id occur when saving category');
        }
    }
 	
 	function actionRename(){
 		$cate = Category::find('category_id=?',$this->_context->category_id)->forUpdate()->getOne();
 		$newName = trim($this->_context->new_name);
 		
 		if($cate->id() && $newName){
 			$cate->name = $newName;
 			$cate->save();
 		}
 		
 		$ret = array(
			'ack' => 'success',
		);
		
		Category::cleanCache();
		
		return json_encode($ret);
 	}
 	
 	function actionRemove(){
 		
 		$cate = Category::find('category_id=?',$this->_context->category_id)->getOne();

		try{
			$cate->destroy();
			$ret = array(
  			'ack' => 'success',
   		);
   		
   		Category::cleanCache();
		}catch(Exception $e){
			$ret = array(
 				'ack' => 'error',
 				'errorMsg' => $e->getMessage(),
 			);
		}
		
		
		return json_encode($ret);
 	}
 	
 	function actionResort(){
 		$ids = Q::normalize($this->_context->ids);
 		
 		foreach($ids as $i => $id){
 			$cate = Category::find('category_id=?',$id)->getOne();
 			if($cate->id()){
 				$cate->sort = $i;
 				$cate->save();
 			}
 		}
 		
 		Category::cleanCache();
 		$ret = array(
			'ack' => 'success',
 		);
 		return json_encode($ret);
 	}

    function actionEdit(){
        $id = $this->_context->cid;
        $cate = Category::findById($id)->getOne();
        $this->_view['cate'] = $cate;
    }
}